<template>
	<view class="strategy-edit-page">
		<!-- 顶部导航栏 -->
		<nav-bar :title="isEdit ? '编辑营销策略' : '创建营销策略'" />

		<!-- 表单内容区域 -->
		<scroll-view scroll-y class="form-scroll">
			<view class="form-container">
				<!-- 使用uni-forms组件进行表单验证和提交 -->
				<uni-forms ref="formsRef" :modelValue="formData" :rules="rules" validate-trigger="submit">

					<!-- 策略标题卡片 -->
					<view class="form-card">
						<view class="card-header">
							<text class="card-icon">✏️</text>
							<text class="card-title">策略标题</text>
						</view>
						<uni-forms-item name="title">
							<uni-easyinput v-model="formData.title" placeholder="给你的策略起个吸引人的名字" maxlength="50"
								placeholderStyle="color: #94a3b8;" />
						</uni-forms-item>
					</view>

					<!-- 产品分类卡片 -->
					<view class="form-card">
						<view class="card-header">
							<text class="card-icon">📦</text>
							<text class="card-title">产品分类</text>
						</view>
						<uni-forms-item name="category">
							<uni-data-select v-model="formData.category"
								:localdata="categories.map(c => ({ text: c, value: c }))" placeholder="选择适合的产品分类" />
						</uni-forms-item>
					</view>

					<!-- 媒体类型卡片 -->
					<view class="form-card">
						<view class="card-header">
							<text class="card-icon">🎨</text>
							<text class="card-title">媒体类型</text>
						</view>
						<uni-forms-item name="mediaType">
							<view class="media-type-selector">
								<!-- 图片类型选项 -->
								<view class="media-type-option" :class="{ active: formData.mediaType === 'image' }"
									@tap="handleMediaTypeChange('image')">
									<text class="media-type-icon">🖼️</text>
									<text class="media-type-text">图片</text>
								</view>
								<!-- 视频类型选项 -->
								<view class="media-type-option" :class="{ active: formData.mediaType === 'video' }"
									@tap="handleMediaTypeChange('video')">
									<text class="media-type-icon">🎥</text>
									<text class="media-type-text">视频</text>
								</view>
							</view>
						</uni-forms-item>
					</view>

					<!-- 媒体上传卡片 -->
					<view class="form-card">
						<view class="card-header">
							<text class="card-icon">📸</text>
							<text class="card-title">上传{{ formData.mediaType === 'image' ? '图片' : '视频' }}</text>
							<text
								class="card-tip">{{ formData.mediaType === 'image' ? '支持 JPG、PNG 格式' : '支持 MP4 格式' }}</text>
						</view>
						<uni-forms-item name="mediaUrl">
							<!-- 文件选择器组件 -->
							<uni-file-picker :limit="1" :del-icon="true" disable-preview="false"
								:imageStyles="imageStyles" v-model="pickerAvatar"
								:file-mediatype="formData.mediaType === 'image' ? 'image' : 'video'"
								@select="handleMediaSelect" @delete="handleDeleteSelect">
							</uni-file-picker>

							<!-- 视频预览区域（仅视频类型且有媒体文件时显示） -->
							<view v-if="formData.mediaType === 'video' && formData.mediaUrl" class="video-preview">
								<video
									:src="formData.mediaUrl.startsWith('http') ? formData.mediaUrl : (baseURL + formData.mediaUrl)"
									controls style="width: 100%; max-height: 240px; border-radius: 12rpx;"></video>
							</view>
						</uni-forms-item>
					</view>

					<!-- 策略描述卡片 -->
					<view class="form-card">
						<view class="card-header">
							<text class="card-icon">📝</text>
							<text class="card-title">策略描述</text>
							<text class="card-tip">详细描述你的营销策略</text>
						</view>
						<uni-forms-item name="description">
							<uni-easyinput v-model="formData.description" type="textarea"
								placeholder="介绍一下这个营销策略的亮点和优势..." :rows="8" maxlength="-1"
								placeholderStyle="color: #94a3b8;" />
						</uni-forms-item>
					</view>

				</uni-forms>
			</view>
		</scroll-view>

		<!-- 底部操作按钮区域 -->
		<view class="action-footer">
			<view class="footer-container">
				<!-- 取消按钮 -->
				<button class="cancel-button" @click="handleBack">
					<text class="button-text">取消</text>
				</button>
				<!-- 提交按钮 -->
				<button class="submit-button" @click="handleSubmit" :disabled="isLoading">
					<text class="button-icon" v-if="!isLoading">{{ isEdit ? '✓' : '✓' }}</text>
					<text class="button-text">{{ isEdit ? '保存修改' : '立即发布' }}</text>
				</button>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	// ==================== 导入依赖 ====================
	import { ref, watch, onMounted, nextTick, computed, onBeforeUnmount } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import { getCategories, addStrategy, updateStrategy, getStrategiesById } from '@/services/marketing';
	import { uploadUserAvatar } from '@/services/user';
	import type { OperationStrategy } from '@/types/marketing';
	import { FileType } from '../../../types/global';
	import { baseURL } from '@/utils/config';
	import { showToast, showLoading, hideLoading, getSafeAreaTop, navigateBack } from '@/utils/global';
	import NavBar from '@/components/nav-bar.vue';
	import { getThemeStyles } from '@/stores/theme';

	// ==================== 组件引用 ====================
	/** 表单组件引用，用于表单验证 */
	const formsRef = ref<any>(null);

	// ==================== 表单验证规则 ====================
	/** 表单字段验证规则配置 */
	const rules = {
		title: {
			required: true,
			maxLength: 40, // 一般1个汉字=3字节，255字节约85字符
			errorMessage: '请输入策略标题'
		},
		category: {
			required: true,
			maxLength: 10,
			errorMessage: '请选择产品分类'
		},
		description: {
			required: true,
			maxLength: 1000,
			errorMessage: '请输入策略描述'
		},
		mediaUrl: {
			required: true,
			errorMessage: '请上传媒体文件'
		}
	};

	// ==================== 文件选择器样式配置 ====================
	/** 文件选择器图片样式配置 */
	const imageStyles = ref({
		width: 200,
		height: 200,
		border: {
			radius: '50%'
		}

	})

	// ==================== 响应式数据 ====================
	/** 是否为编辑模式 */
	const isEdit = ref<boolean>(false);
	/** 是否正在加载中 */
	const isLoading = ref<boolean>(false);
	/** 产品分类列表 */
	const categories = ref<string[]>([]);

	const formData = ref<Partial<OperationStrategy>>({
		title: '',
		description: '',
		mediaType: 'image',
		mediaUrl: '',
		poster: '',
		category: ''
	});

	const editingStrategy = ref<OperationStrategy | null>(null);
	/**
	 * 用户头像
	 */
	const pickerAvatar = ref<FileType[]>([]);

	const safeAreaTop = ref<number>(0);

	// ==================== 主题相关 ====================
	/** 获取当前主题样式 */
	const themeStyles = computed(() => getThemeStyles());

	// ==================== 生命周期钩子 ====================
	/** 页面加载时获取参数 */
	onLoad((options : any) => {
		// 查询分类数据
		initCategories();
		// 从路由参数获取 strategyId
		if (options.strategyId) {
			// 编辑模式
			isEdit.value = true;
			loadStrategyData(options.strategyId);
		}
	});

	/** 组件挂载完成后执行 */
	onMounted(() => {
		// 如果是编辑模式，等待数据加载完成后再设置预览
		if (isEdit.value && editingStrategy.value) {
			setupEditMode();
		}
		safeAreaTop.value = getSafeAreaTop();
		
		// 监听主题变化
		uni.$on('themeChange', () => {
			// 主题切换时，computed 会自动更新
		});
	});

	/** 组件卸载时清理 */
	onBeforeUnmount(() => {
		uni.$off('themeChange');
	});

	// ==================== 编辑模式相关方法 ====================
	/** 设置编辑模式，初始化表单数据和预览 */
	const setupEditMode = () => {
		if (editingStrategy.value) {
			formData.value = { ...editingStrategy.value };

			// 如果有媒体文件，设置预览
			if (formData.value.mediaUrl) {
				setPickerPreview(formData.value.mediaUrl);
				console.log("设置编辑模式预览:", pickerAvatar.value);
			} else {
				// 如果没有媒体文件，清空选择器
				pickerAvatar.value = [];
			}
		}
	};

	/** 加载策略数据（编辑模式使用） */
	const loadStrategyData = async (strategyId : number) => {
		try {
			const response = await getStrategiesById(strategyId);
			editingStrategy.value = response.data;

			// 数据加载完成后，设置编辑模式
			nextTick(() => {
				setupEditMode();
			});
		} catch (error) {
			console.error('获取策略详情失败:', error);
			showToast('获取策略详情失败，请重试', 'none');
		}
	};

	/** 初始化分类数据 */
	const initCategories = async () => {
		try {
			const categoriesData = await getCategories();
			categories.value = categoriesData.data;
		} catch (error) {
			console.error('获取分类列表失败:', error);
			showToast('获取分类失败，请重试', 'none');
		}
	};



	// ==================== 监听器 ====================
	/** 监听媒体类型变化，重置相关字段 */
	watch(() => formData.value.mediaType, (newType) => {
		if (newType === 'image') {
			formData.value.poster = '';
		}
	});

	// ==================== 页面操作方法 ====================
	/** 返回上一页 */
	const handleBack = () => {
		navigateBack();
	};

	// ==================== 媒体数据处理方法 ====================
	/** 设置文件选择器预览 */
	const setPickerPreview = (mediaUrl : string) => {
		pickerAvatar.value = [{
			url: baseURL + mediaUrl,
			extname: '',
			name: mediaUrl?.split('/').pop() || ''
		}];
	};

	/** 清空媒体数据 */
	const clearMediaData = () => {
		formData.value.mediaUrl = '';
		formData.value.poster = '';
		pickerAvatar.value = [];
	};



	// ==================== 媒体类型变更处理 ====================
	/** 处理媒体类型变更（图片/视频切换） */
	const handleMediaTypeChange = (type : 'image' | 'video') => {
		// 如果类型相同，不需要切换
		if (formData.value.mediaType === type) {
			return;
		}

		// 如果媒体文件已存在，就只切换类型不清空，保持当前媒体数据
		if (formData.value.mediaUrl) {
			formData.value.mediaType = type;
			// 保持现有数据，不清空
		} else {
			// 没有媒体，正常切换并清空
			formData.value.mediaType = type;
			clearMediaData();
		}

		// 清除验证提示
		formsRef.value?.clearValidate('mediaUrl');
	};



	// ==================== 媒体文件操作处理 ====================
	/** 处理媒体移除事件，清除相关字段值 */
	const handleDeleteSelect = () => {
		clearMediaData();
		// 清除验证提示
		formsRef.value?.clearValidate('mediaUrl');
	};

	/** 处理媒体文件选择 */
	const handleMediaSelect = (file : any) => {
		console.log('选择的媒体文件:', file);
		// 检查是否有选择文件
		if (file && file.tempFiles && file.tempFiles.length > 0) {
			const selectedFile = file.tempFiles[0];
			// 设置临时预览
			pickerAvatar.value = [{
				url: selectedFile.url,
				extname: selectedFile.extname,
				name: selectedFile.name
			}];
			// 调用上传函数
			uploadUserAvatar(selectedFile)
				.then(handleMediaUploadSuccess)
				.catch(handleMediaUploadFail);
		}
	};




	// ==================== 媒体上传处理 ====================
	/** 媒体上传成功处理 */
	const handleMediaUploadSuccess = (response : any) => {
		console.log('媒体上传成功:', response);
		formData.value.mediaUrl = response.url;
		// 如果是视频，设置海报
		if (formData.value.mediaType === 'video' && response.thumbnail) {
			formData.value.poster = response.thumbnail;
		}
		// 更新预览为服务器URL
		setPickerPreview(response.url);
		showToast('上传成功', 'success');
		// 清除验证提示
		formsRef.value?.clearValidate('mediaUrl');
	};

	/** 媒体上传失败处理 */
	const handleMediaUploadFail = (error : any) => {
		console.error('媒体上传失败:', error);
		// 上传失败时清空预览
		clearMediaData();
		showToast('上传失败，请重试', 'none');
	};



	// ==================== 表单提交处理 ====================
	/** 准备策略数据（用于提交） */
	const prepareStrategyData = () : OperationStrategy => {
		return {
			...(formData.value as OperationStrategy),
			id: editingStrategy.value?.id
		} as OperationStrategy;
	};

	/** 执行保存操作（新增或更新） */
	const executeSave = async (strategyData : OperationStrategy) => {
		if (isEdit.value) {
			await updateStrategy(strategyData);
			showToast('更新成功', 'success');
		} else {
			await addStrategy(strategyData);
			showToast('添加成功', 'success');
		}
	};

	/** 提交表单（主要提交逻辑） */
	const handleSubmit = async () => {
		try {
			// 使用uni-forms的验证
			await formsRef.value.validate();

			showLoading(isEdit.value ? '更新中...' : '保存中...');
			isLoading.value = true;

			// 准备并执行保存
			const strategyData = prepareStrategyData();
			await executeSave(strategyData);

			// 保存成功后返回上一页
			setTimeout(() => {
				navigateBack();
			}, 1500);
		} catch (error : any) {
			// 表单验证失败时，uni-forms会自动显示错误信息
			if (error?.message) {
				console.error('保存策略失败:', error);
				showToast(isEdit.value ? '更新失败' : '添加失败', 'none');
			}
		} finally {
			hideLoading();
			isLoading.value = false;
		}
	};


	// emit通知
</script>

<style scoped>
	/* 页面容器 */
	.strategy-edit-page {
		width: 100%;
		height: 100vh;
		background: v-bind('themeStyles.primaryGradient');
		display: flex;
		flex-direction: column;
		overflow: hidden;
	}

	/* 表单滚动区域 */
	.form-scroll {
		flex: 1;
		width: 100%;
		height: 0;
		/* 关键：flex子元素需要设置height: 0才能正确计算flex高度 */
		background: v-bind('themeStyles.bgSecondary');
	}

	/* 表单容器 */
	.form-container {
		padding: 24rpx;
		padding-bottom: 160rpx;
	}

	/* 表单卡片 */
	.form-card {
		background: v-bind('themeStyles.bgCard');
		border-radius: 24rpx;
		padding: 32rpx;
		margin-bottom: 24rpx;
		box-shadow: v-bind('themeStyles.cardBoxShadow');
		border: v-bind('themeStyles.cardBorder');
		transition: all 0.3s ease;
		position: relative;
		z-index: 1;
	}

	.form-card:hover {
		box-shadow: v-bind('themeStyles.hoverShadow');
		transform: translateY(-2rpx);
	}

	/* 确保下拉选择器的卡片层级更高 */
	.form-card:nth-child(2) {
		z-index: 10;
	}

	/* 卡片头部 */
	.card-header {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;
		padding-bottom: 20rpx;
		border-bottom: 2rpx solid v-bind('themeStyles.borderLight');
	}

	.card-icon {
		font-size: 40rpx;
		margin-right: 16rpx;
	}

	.card-title {
		font-size: 32rpx;
		font-weight: 600;
		color: v-bind('themeStyles.textPrimary');
		flex: 1;
	}

	.card-tip {
		font-size: 24rpx;
		color: v-bind('themeStyles.textPlaceholder');
		margin-left: auto;
	}




	/* 媒体类型选择器 */
	.media-type-selector {
		display: flex;
		gap: 20rpx;
		flex: 1;
	}

	/* 媒体类型选项 */
	.media-type-option {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 32rpx 20rpx;
		border: 3rpx solid v-bind('themeStyles.borderColor');
		border-radius: 20rpx;
		background: v-bind('themeStyles.bgCard');
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		position: relative;
		overflow: hidden;
		cursor: pointer;
	}

	.media-type-option::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: v-bind('themeStyles.primaryGradient');
		opacity: 0;
		transition: opacity 0.3s ease;
	}

	.media-type-option.active {
		border-color: v-bind('themeStyles.primaryColor');
		background: v-bind('themeStyles.accentBg');
		transform: translateY(-4rpx);
		box-shadow: v-bind('themeStyles.buttonBoxShadow');
	}

	.media-type-option.active .media-type-icon {
		transform: scale(1.2);
		filter: drop-shadow(0 4rpx 8rpx v-bind('themeStyles.primaryColor'));
	}

	.media-type-option.active .media-type-text {
		color: v-bind('themeStyles.primaryColor');
		font-weight: 700;
	}

	/* 媒体类型图标 */
	.media-type-icon {
		font-size: 48rpx;
		margin-bottom: 12rpx;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		position: relative;
		z-index: 1;
	}

	/* 媒体类型文本 */
	.media-type-text {
		font-size: 28rpx;
		color: v-bind('themeStyles.textSecondary');
		font-weight: 500;
		transition: all 0.3s ease;
		position: relative;
		z-index: 1;
	}

	/* 媒体上传器 */
	.media-uploader {
		flex: 1;
		margin-top: 8rpx;
		width: 100%;
		overflow: hidden;
	}

	/* 媒体预览 */
	.media-preview {
		position: relative;
		width: 100%;
		height: 280rpx;
		border-radius: 16rpx;
		overflow: hidden;
		background: v-bind('themeStyles.bgSecondary');
		box-shadow: v-bind('themeStyles.shadowSm');
		border: 1rpx solid v-bind('themeStyles.borderColor');
	}

	/* 预览图片和视频 */
	.preview-image,
	.preview-video {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	/* 媒体覆盖层 */
	.media-overlay {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(to bottom, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0.3) 100%);
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		padding: 16rpx;
	}

	/* 媒体类型徽章 */
	.media-type-badge {
		align-self: flex-start;
		background: rgba(0, 0, 0, 0.7);
		color: #fff;
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		font-weight: 500;
		backdrop-filter: blur(10rpx);
	}

	.media-type-badge.image {
		background: #3b82f6;
	}

	.media-type-badge.video {
		background: #10b981;
	}

	/* 媒体操作按钮容器 */
	.media-actions {
		align-self: flex-end;
	}

	/* 移除媒体按钮 */
	.remove-media-btn {
		display: flex;
		align-items: center;
		gap: 6rpx;
		background: #ef4444;
		color: #fff;
		padding: 12rpx 20rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		font-weight: 500;
		border: none;
		box-shadow: 0 4rpx 15rpx rgba(239, 68, 68, 0.2);
		transition: all 0.3s ease;
	}

	.remove-media-btn:hover {
		transform: translateY(-2rpx);
		box-shadow: 0 6rpx 20rpx rgba(240, 147, 251, 0.4);
	}

	/* 上传区域 */
	.upload-area {
		width: 100%;
		height: 280rpx;
		border: 2rpx dashed v-bind('themeStyles.borderColor');
		border-radius: 16rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background: v-bind('themeStyles.bgSecondary');
		transition: all 0.3s ease;
		position: relative;
		overflow: hidden;
	}

	.upload-area:hover {
		border-color: v-bind('themeStyles.primaryColor');
		background: v-bind('themeStyles.accentBg');
		transform: translateY(-2rpx);
		box-shadow: v-bind('themeStyles.shadowSm');
	}

	.upload-area:hover .upload-icon {
		transform: scale(1.1);
		opacity: 1;
	}

	/* 上传内容 */
	.upload-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		text-align: center;
	}

	/* 上传图标 */
	.upload-icon {
		font-size: 80rpx;
		margin-bottom: 16rpx;
		opacity: 0.6;
		transition: all 0.3s ease;
	}

	/* 上传文本 */
	.upload-text {
		font-size: 28rpx;
		color: v-bind('themeStyles.textPrimary');
		font-weight: 500;
		margin-bottom: 8rpx;
	}

	/* 上传描述 */
	.upload-desc {
		font-size: 24rpx;
		color: v-bind('themeStyles.textTertiary');
	}

	/* 底部操作区域 */
	.action-footer {
		position: fixed;
		left: 0;
		bottom: 0;
		right: 0;
		z-index: 999;
		background: v-bind('themeStyles.bgCard');
		backdrop-filter: blur(20rpx);
		padding: 24rpx 32rpx;
		padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
		box-shadow: v-bind('themeStyles.cardBoxShadow');
		border-top: 1rpx solid v-bind('themeStyles.borderLight');
	}

	.footer-container {
		display: flex;
		gap: 20rpx;
		max-width: 750rpx;
		margin: 0 auto;
	}

	/* 取消按钮 */
	.cancel-button {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 8rpx;
		padding: 28rpx 24rpx;
		background: v-bind('themeStyles.bgCard');
		color: v-bind('themeStyles.textSecondary');
		border: 3rpx solid v-bind('themeStyles.borderColor');
		border-radius: 20rpx;
		font-size: 32rpx;
		font-weight: 600;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		box-shadow: v-bind('themeStyles.shadowSm');
	}

	.cancel-button:active {
		background: v-bind('themeStyles.bgSecondary');
		border-color: v-bind('themeStyles.borderLight');
		transform: scale(0.98);
	}

	/* 提交按钮 */
	.submit-button {
		flex: 2;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 12rpx;
		padding: 28rpx 24rpx;
		background: v-bind('themeStyles.primaryGradient');
		color: #ffffff;
		border: none;
		border-radius: 20rpx;
		font-size: 32rpx;
		font-weight: 700;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		box-shadow: v-bind('themeStyles.buttonBoxShadow');
		position: relative;
		overflow: hidden;
	}

	.submit-button::before {
		content: '';
		position: absolute;
		top: 0;
		left: -100%;
		width: 100%;
		height: 100%;
		background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
		transition: left 0.5s ease;
	}

	.submit-button:active:not(:disabled) {
		transform: scale(0.98);
		box-shadow: v-bind('themeStyles.cardBoxShadow');
	}

	.submit-button:active:not(:disabled)::before {
		left: 100%;
	}

	.submit-button:disabled {
		opacity: 0.5;
		cursor: not-allowed;
		transform: none;
		box-shadow: v-bind('themeStyles.cardBoxShadow');
	}

	/* 按钮图标 */
	.button-icon {
		font-size: 32rpx;
		font-weight: bold;
	}

	/* 按钮文本 */
	.button-text {
		font-size: 32rpx;
		font-weight: 600;
	}
</style>